﻿using System.IO;
using System.Linq;

namespace RIFF.Chunk
{
    /// <summary>
    /// RIFF Chunk。整个文件中只允许顶级 Chunk  是 RIFF Chunk，且必须是。
    /// </summary>
    public class Riff : ListBase
    {
        /// <summary>
        /// 类型。通常是文件格式类型，如 WAVE。
        /// </summary>
        public FourCC FormType => listType;


        /// <summary>
        /// 克隆一个 Chunk，将其解释为 RIFF Chunk
        /// </summary>
        /// <exception cref="ChunkIdException"/>
        /// <param name="chunk">克隆源</param>
        public Riff(Chunk chunk) : base(chunk)
        {
            if (chunk.Id.ToString() != "RIFF")
            {
                throw new ChunkIdException("RIFF", Id.ToString());
            }
        }

        /// <summary>
        /// 查找 SubChunks 中 Data Chunk
        /// </summary>
        /// <exception cref="MissingDataChunkException"></exception>
        /// <returns>SubChunks 中第一个 Data Chunk</returns>
        public Data GetDataChunk()
        {
            if (!SubChunks.Where(c => c is Data).Any())
            {
                throw new MissingDataChunkException("RIFF Chunk 未包含子 Chunk");
            }

            return (Data)SubChunks.Where(c => c is Data).First();
        }


        /// <summary>
        /// 查找 SubChunks 中 Format Chunk
        /// </summary>
        /// <exception cref="MissingFormatChunkException"/>
        /// <returns>SubChunks 中第一个 Format Chunk</returns>
        public Format GetFormatChunk()
        {
            if (!SubChunks.Where(c => c is Format).Any())
            {
                throw new MissingFormatChunkException("RIFF Chunk 未包含 Format Chunk");
            }

            return (Format)SubChunks.Where(c => c is Format).First();
        }

        // TODO: 关闭流
        // TODO: 实现异步
        public static Riff Open(string fileName)
        {
            var chunk = new Chunk(File.OpenRead(fileName));
            return chunk.ToRiffChunk();
        }


    }
}
